package com.lenovo.leos.letools.lenovodata;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.lenovo.leos.letools.exception.NetException;
import com.lenovo.leos.letools.exception.PreUploadException;
import com.lenovo.leos.letools.net.HttpGet;
import com.lenovo.leos.letools.net.HttpPost;
import com.lenovo.leos.letools.net.ResponseValue;
import com.lenovo.leos.letools.utils.Constants;
import com.lenovo.leos.letools.utils.CookieStore;
import com.lenovo.leos.letools.utils.ListFileUseParams;
import com.lenovo.leos.letools.utils.StreamTool;

public class BaseNetClientServer {


	/**
	 * 登录
	 * 
	 * @param context
	 * @param userid
	 * @param password
	 * @return
	 * @throws NetException 
	 * @throws Exception
	 */
	public String login(Context context,String userid, String password) throws NetException {
		String urlpath = Constants.LENOVODATA_LOGIN;
		String urlParameters = "userid=" + userid + "&password=" + password;
		// String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlParameters, null);
			ResponseValue resVal = post.doPost();
			// 将名为AUTH_PRO的cookie保持到文件中
			String auth_pro = "";
			for (String cookieVal : resVal.getCookies()) {
				if (cookieVal.contains("AUTH_PRO")) {
					auth_pro = cookieVal;
					Log.i("cookie", "===========" + auth_pro);
					break;
				}
			}
			CookieStore.addCookie(context, auth_pro);
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(post!=null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 得到网盘的空间使用情况
	 * 
	 * @return
	 * @throws NetException 
	 */
	public String getSpace(Context context) throws NetException {
		String urlpath = Constants.LENOVODATA_GETSPACE;
		String cookieValue = CookieStore.getCookie(context);// auth
		HttpGet get=null;
		String jsonVal = "";
		try{
			get = new HttpGet(urlpath, cookieValue);
			ResponseValue resVal = get.doGet();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(get!=null)
				get.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 得到指定目录下的所有子目录及文件个数
	 * 
	 * @param dirid
	 * @return
	 * @throws NetException 
	 */
	public String listDir(Context context, String dirid) throws NetException {
		String urlpath = Constants.LENOVODATA_DIR_LIST + dirid;
		String cookieValue = CookieStore.getCookie(context);// auth
		HttpGet get = null;
		String jsonVal = "";
		try{
			get = new HttpGet(urlpath, cookieValue);
			ResponseValue resVal = get.doGet();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(get!=null)
				get.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 创建目录
	 * 
	 * @param parentid
	 * @param dirname
	 * @return
	 */
	public String createDir(Context context, String parentid, String dirname)  throws NetException {
		String urlpath = Constants.LENOVODATA_DIR_CREATE;
		String urlParameters = "parentid=" + parentid + "&dirname=" + dirname;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlParameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(post!=null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 删除目录
	 * 
	 * @param dirid
	 * @return
	 */
	public String delDir(Context context, String dirid)  throws NetException {
		String urlpath = Constants.LENOVODATA_DIR_DELETE;
		String urlparameters = "dirid=" + dirid;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try {
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		} finally {
			if (post != null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 重命名目录
	 * 
	 * @param dirid
	 * @param dirname
	 * @return
	 */
	public String renameDir(Context context, String dirid, String dirname)  throws NetException {
		String urlpath = Constants.LENOVODATA_DIR_RENAME;
		String urlparameters = "dirid=" + dirid + "&dirname=" + dirname;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try {
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		} finally {
			if (post != null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 移动目录
	 * 
	 * @param dirid
	 * @param targetid
	 * @return
	 */
	public String moveDir(Context context, String dirid, String targetid) throws NetException  {
		String urlpath = Constants.LENOVODATA_DIR_MOVE;
		String urlparameters = "dirid=" + dirid + "&targetid=" + targetid;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post=null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(post!=null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 列出指定目录下的所有文件
	 * 
	 * @param params
	 * @param context
	 * @return
	 * @throws NetException 
	 */
	public String listFile(Context context, ListFileUseParams params) throws NetException {
		String urlpath = Constants.LENOVODATA_FILE_LIST + params.dirid
				+ "/TEXT/timedesc/0/10";
		String cookieValue = CookieStore.getCookie(context);// auth
		HttpGet get = null;
		String jsonVal = "";
		try{
			get = new HttpGet(urlpath, cookieValue);
			ResponseValue resVal = get.doGet();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(get!=null)
				get.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 删除指定文件
	 * 
	 * @param fileid
	 * @return
	 */
	public String deleteFile(Context context, String fileid)  throws NetException {
		String urlpath = Constants.LENOVODATA_FILE_DELETE;
		String urlparameters = "fileid=" + fileid;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(post!=null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 重命名指定文件
	 * 
	 * @param fileid
	 * @param filename
	 * @return
	 */
	public String renameFile(Context context, String fileid, String filename)  throws NetException {
		String urlpath = Constants.LENOVODATA_FILE_RENAME;
		String urlparameters = "fileid=" + fileid + "&filename=" + filename;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		}finally{
			if(post!=null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 移动文件
	 * 
	 * @param targetid
	 * @param fileid
	 * @param override
	 * @return
	 */
	public String moveFile(Context context, String targetid, String fileid,
			String override)  throws NetException {
		String urlpath = Constants.LENOVODATA_FILE_MOVE;
		String urlparameters = "fileid=" + fileid + "&targetid=" + targetid
				+ "&override" + override;
		String cookieValue = CookieStore.getCookie(context);
		HttpPost post = null;
		String jsonVal = "";
		try {
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			// 返回请求的json数据
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
		} finally {
			if (post != null)
				post.closeConn();
		}
		return jsonVal;
	}

	/**
	 * 预下载文件
	 * 
	 * @param context
	 * @param fileid
	 * @return
	 * 返回的cookie信息
	 * 	 正确访问的返回cookie值
		   PHPSESSID=2m54ir5rrt67svihnsf9ohvrd4
		   FILENAME=hongchen.jpg
	       FILELENGTH=1890410
	       TOKEN=9783bd269fe8bd71bdb5de2d316b1aab0771759e8be689c932c55226d8444242392c941cbf4375ec92c934850edc0677bfbf7d16136c4a6a57e6b91744e307cba62c44c380539448fc6be797566b73b2bff35730fe770a44
	           错误访问的返回cookie值 null
	       返回的数据信息
	       	正确访问的返回值https://tp.vips100.com
	       	错误访问的返回值 null
	 * @throws NetException 
	 */
	public List<String> predownload(Context context, String fileid) throws NetException {
		if(fileid==null) fileid="";
		String urlpath = Constants.LENOVODATA_FILE_PRODOWNLOAD + fileid.trim();
		String cookieValue = CookieStore.getCookie(context);// auth
		HttpGet get = null;
		ResponseValue resVal = new ResponseValue();
		try{
			get = new HttpGet(urlpath, cookieValue);
			resVal = get.doGet();
//			for (String cookieVal : resVal.getCookies()) {
//				if (cookieVal.contains("TOKEN")) {
//					token = cookieVal;
//				}
//				if (cookieVal.contains("FILENAME")) {
//					filename = cookieVal.substring(cookieVal.indexOf("=") + 1);
//				}
//			}
		}finally{
			if(get!=null)
				get.closeConn();
		}
		return resVal.getCookies();
	}

	/**
	 * 预上传文件
	 * 
	 * @param dirid
	 * @param filename
	 * @param size
	 * @param lastmodifytime
	 * @param override
	 * @return  返回值包括  正常的返回值中筛选出fileid和cookie为token的值 
	 * 			map中包含两个key-value对 分别是 key = fileid和key = cookie_token
	 * @throws PreUploadException 
	 * @throws Exception
	 * 
	 * /**
	 * 预上传 returnval(2181):1301295060027207526.txt|9e85990856f8fb00989f1b1d5678e437e71e6df383bd5927769d6e18e01e575ce101545ffc5ba52fa0effe1e4f5103a8cc47867e432d6e20614e0ec19bfc2a5916d595ad2764a0de3316576e17d0ac031a8fb8fca90c4da932203f93
	 * |https://tp.vips100.com PHPSESSID=5jn0uk8u1icoauokgiuiduupo6
	 * TOKEN=9e85990856f8fb00989f1b1d5678e437e71e6df383bd5927769d6e18e01e575ce101545ffc5ba52fa0effe1e4f5103a8cc47867e432d6e20614e0ec19bfc2a5916d595ad2764a0de3316576e17d0ac031a8fb8fca90c4da932203f93
	 * 
	 */
	public Map<String,String> preupload(Context context, String dirid, String filename,
			String size, String lastmodifytime, String override)
			throws NetException, PreUploadException {
		String urlpath = Constants.LENOVODATA_FILE_PROUPLOAD;
		String urlparameters = "dirid=" + dirid + "&filename=" + filename
				+ "&size=" + size + "&lastmodifytime=" + lastmodifytime
				+ "&over_ride=" + override;
		String cookieValue = CookieStore.getCookie(context);
		Map<String,String> tokenFileidAndUrl = new HashMap<String,String>();
		HttpPost post = null;
		String jsonVal = "";
		try{
			post = new HttpPost(urlpath, urlparameters, cookieValue);
			ResponseValue resVal = post.doPost();
			//返回的cookie信息
			for (String cookieVal : resVal.getCookies()) {
				Log.i("cookie", "===========" + cookieVal);
				if (cookieVal.contains("TOKEN")) {
					tokenFileidAndUrl.put("cookie_token",cookieVal);
				}
			}
			// 返回请求的json数据  得到请求的返回值，并解析出返回的文件fileid
			jsonVal = StreamTool.parseStream(resVal.getInputStream());
			for(int i=0;i<5;i++){
				Log.d("CLient","###############+++++++++++++++++### jsonVal is: " + jsonVal);
			}
			String fileid = jsonVal.substring(0, jsonVal.indexOf("|"));
			String uploadUrl = jsonVal.substring(jsonVal.lastIndexOf("|")+1);//  url
			tokenFileidAndUrl.put("fileid",fileid);
			tokenFileidAndUrl.put("uploadUrl",uploadUrl);
			
			Log.i("resVal", "===========" + jsonVal);
			if(Constants.STATE_PREUPLOAD_SPACEFULLED.equals(jsonVal)){
				PreUploadException pe = new PreUploadException(Constants.STATE_PREUPLOAD_SPACEFULLED,"空间已满");
				throw pe;
			}
			if(Constants.STATE_PREUPLOAD_FILESIZEMORELENGTH.equals(jsonVal)){
				PreUploadException pe = new PreUploadException(Constants.STATE_PREUPLOAD_FILESIZEMORELENGTH,"文件超过文件尺寸限制");
				throw pe;
			}
			if(Constants.STATE_PREUPLOAD_FILEEXISTED.equals(jsonVal)){
				PreUploadException pe = new PreUploadException(Constants.STATE_PREUPLOAD_FILEEXISTED,"文件名已经存在");
				throw pe;
			}
			if(Constants.STATE_PREUPLOAD_INVALIDFILENAME.equals(jsonVal)){
				PreUploadException pe = new PreUploadException(Constants.STATE_PREUPLOAD_INVALIDFILENAME,"文件名无效");
				throw pe;
			}
		}finally{
			if(post!=null)
				post.closeConn();
		}
		
		return tokenFileidAndUrl;
	}
}
